// *******************************************************************************************************
// # エリア
//   ・検索結果 地図
// *******************************************************************************************************

var ResultBridge = ResultBridge || {};

$(function() {
	var isUnderIe6 = uaInfo.isIe && uaInfo.ieVr <= 6,
		isUnderIe7 = uaInfo.isIe && uaInfo.ieVr <= 7;

	//add 141204 
	var _ary = {};
	var _timer=0;

	var reqKey = null;

	/*******************************************************
	 *　mapArea
	 *******************************************************/
	function mapArea(){
		var x =  $('#keido').val();//503051.63,//502933,
			y =  $('#ido').val();//128698.6,//128472,
			scl = 400,
			K1 = 'apanew',
			K2 = '1205jdwa';

		var map = null,
			ajax = null,
			dtlAjax = [],
			dtlTask = [],
			iconLayer = null,
			timer = null;

		$('#map').on('map.changeAjaxStatus', function () {
			var val = ajax !== null || dtlAjax.length > 0 ? 'visible' : 'hidden';
			$('.map_alert').css('visibility', val);
		});

		dtlAjax.abortAll = function () {
			$(this).each(function(idx, jqxhr) {
				jqxhr.abort();
			});
			this.splice(0, this.length);
			$('#map').triggerHandler('map.changeAjaxStatus');
		};

		dtlTask.clearAll = function () {
			$(this).each(function(idx, task) {
				clearTimeout(task);
			});
			this.splice(0, this.length);
		};

		// map
		map = new Mapple.TouchMap('map', 710, 580, x, y, scl, {
			k1: K1,
			k2: K2,
			mouseWheelMode: 'focus',
			maxScaleLevelLimit: 500,
			beforeAreaAction:beforeAreaAction,
			areaEventAction:areaEventAction
		});

		//add 141204 
		map.setOverlayIconsMultiSelectMode({
			choicesList: false,
			choicesListLayerFilter : false
		});

		function beforeAreaAction(){
			if (timer) {
				clearTimeout(timer);
				timer = null;
			};
			//if (ajax) {
			//	ajax.abort();
			//	ajax = null;
			//};
		};
		function areaEventAction(){
			//beforeAreaAction();
			//timer = setTimeout(ajaxRequest, 500);
			ajaxRequest();
		};

		// icon
		iconLayer = map.createOverlayIcons({
			clickAction: clickAction,

			//add 141204 
			mouseOverAction : mouseOverAction,
			//add 141212 
			mouseOutAction : mouseOutAction
		});

		//add 141212 
		var onTimerControl = function(b){
			if(b){
				if(_timer){clearTimeout(_timer);}
			}else{
				if(_timer){clearTimeout(_timer);}
				_timer = setTimeout(function(){createMapInitHtml()}, 1000);
			}
		}

		//add 141204 
		function mouseOverAction(id){
			//add 141212 
			onTimerControl(true);

			dtlAjax.abortAll();
			dtlTask.push(setTimeout(function () {
				createMapDetailHtml(_ary[id]);
			}, 50));
			//alert("_ary[num]="+_ary[num]["name"]);
		};

		//add 141212
		function mouseOutAction(){
			onTimerControl(false);
			dtlTask.clearAll();
		}

		//add 141212 
		function createMapInitHtml(){
			var dtl = $('.map_detail');
			dtl.first().show();
			dtl.last().hide();
		}

		function changeMapDetail(ary) {
			var dtl = $('.map_detail');
			dtl.find('.date_img2').empty().append('<img src="'+ary["img2"]+'?sr.dw=74&sr.dh=74" alt="物件画像">');
			dtl.find('.date_type').text(ary["type"]);
			dtl.find('.date_name').text(ary["name"]);
			dtl.find('.date_rent1').text(ary["rent1"]);
			dtl.find('.date_rent2').text(ary["rent2"]);
			dtl.find('.date_rooms').text(ary["rooms"]);
			dtl.find('.date_floor').text(ary["floor"]);
			dtl.find('.date_article').text(ary["article"]);
			dtl.first().hide();
			dtl.last().show();
		}

		//add 141212
		function createMapDetailHtml(ary){
			if (ary.hasOwnProperty('name')) {
				changeMapDetail(ary);
				return;
			}
			var params = PrepareParameter();
			params.push({name:'maptarget', value:$('#maptarget').val()});
			params.push({name:'daihyoTatemonoCd', value:ary['id']});
			params.push({name:'mode', value:'json'});
			dtlAjax.push($.ajax({
				beforeSend: function(xhr){
					xhr.overrideMimeType("text/html;charset=UTF-8");
				},
				url: '/rstobi/rstobi',
				type: 'POST',
				data: params,
				success: function(e){
					var items = eval( '(' + e + ')' );
					var item = items['items'][0];
					if (item != null) {
						_ary[item['id']] = item;
						changeMapDetail(item);
					}
				},
				error: function(e){
					//console.dir(e);
				},
				complete: function (jqxhr) {
					var index = dtlAjax.indexOf(jqxhr);
					if (index > -1) {
						dtlAjax.splice(index, 1);
						$('#map').triggerHandler('map.changeAjaxStatus');
					}
				}
			}));
			$('#map').triggerHandler('map.changeAjaxStatus');
		}

		//add 141204 
		function clickAction(id){
			var link = '/article/' + id + '/';
			window.open(link,'_blank');
			
		};

		var iconOption = {
			normalSrc: '/static/shared/images/icon/map/icon_home.png',
			//highlightSrc: '/shared/images/icon/map/icon_home.png',
			clickMove: false,
			cursor: 'pointer',
			scaleLevel: null,

			//add 141204 comment out
			//name: _item['name'],
			normal: {
				leftOffset: -20,
				leftOffsetUnit: 'pixels',
				topOffset: 60,
				topOffsetUnit: 'pixels',
				scale: 1.0
			},
			highlight: {
				leftOffset: -20,
				leftOffsetUnit: 'pixels',
				topOffset: 60,
				topOffsetUnit: 'pixels',
				scale: 1.0
			}
		};

		// ajax
		function ajaxRequest(){
			var rect = map.getRectLocations();
			var params = PrepareParameter();
			params.push({name:'maptarget', value:$('#maptarget').val()});
			params.push({name:'lng1', value:rect[1].x / 3600});
			params.push({name:'lat1', value:rect[1].y / 3600});
			params.push({name:'lng3', value:rect[3].x / 3600});
			params.push({name:'lat3', value:rect[3].y / 3600});
			params.push({name:'mode', value:'json'});
			params.push({name:'reqKey', value:reqKey});

			ajax = $.ajax({
				beforeSend: function(xhr){
			    	 xhr.overrideMimeType("text/html;charset=UTF-8");
				},
				url: '/rstobi/rstobi', //'/static/area/json/mapple_sample.txt',
				type: 'post',				
				data: params,
				success: function(e){
					var items = eval( '(' + e + ')' );
					reqKey = items['reqKey'];
					//iconLayer.removeAll();
					var len = items['items'].length;	
					//alert(len);
					var ids = [];
					for (var i = 0; i < len; i++) {
						var _item = items['items'][i];
						//add 141204 
						//_ary.push(_item['name']);
						_ary[_item['id']] = _item;
						ids.push(_item['id']);
						if (ids.length >= 50) {
							getDetail(ids);
							ids = [];
						}
						iconLayer.append(_item['id'], _item['x'], _item['y'], iconOption);
						//console.log("name="+_item['name']);
					}
					getDetail(ids);
				},
				error: function(e){
					//console.dir(e);
				},
				complete: function () {
					ajax = null;
					$('#map').triggerHandler('map.changeAjaxStatus');
				}
			});
			$('#map').triggerHandler('map.changeAjaxStatus');
		};
		
		ajaxRequest();
	};


	/*******************************************************
	 * scroll
	 *******************************************************/
	function scrollSetting(){
		var $target = $('#contentMainColumn .mod_box_section.box_map'),
			tp = $target.offset().top,
			np = $('#contentMainColumn .mod_ttl_bar_sublink').height() + $('#contentMainColumn nav').height(),
			wp = $('#wrapper').height(),
			sc = 0,
			mp = 64,
			hp = 600;

		function scroll(){
			if (isUnderIe6) return;
			if (sc < tp - mp) {
				$target.css({ position: 'absolute', top: np });
			} else if (sc > wp - hp + mp) {
				$target.css({ position: 'absolute', top: wp - hp - 20 });
			} else {
				$target.css({ position: 'fixed', top: mp });
			};
		};

		$(window).on('scroll', function(e){
			sc = $(window).scrollTop();
			scroll();
		}).trigger('scroll');

		ResultBridge.callBackCtsHeightEvent = function() {
			wp = $('#wrapper').height();
			$(window).trigger('scroll');
		};
	};


	// init
	mapArea();	
	scrollSetting();
	$(window).on('unload', function () {
		$.ajax({
			type: 'POST',
			async: false,
			url: '/areaajax/getmap/',
			data: 'reqKey=' + reqKey,
			dataType: "json",
			success: function(data) {
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
			}
		});
	});
	// 物件情報を取得する
	function getDetail(ids) {
		if (ids.length === 0) {
			return;
		}
		var params = PrepareParameter();
		params.push({name:'maptarget', value:$('#maptarget').val()});
		for (var i = 0; i < ids.length; i++) {
			params.push({name:'daihyoTatemonoCd[]', value:ids[i]});
		}
		params.push({name:'mode', value:'json'});
		$.ajax({
			beforeSend: function(xhr){
				xhr.overrideMimeType("text/html;charset=UTF-8");
			},
			url: '/rstobi/rstobi',
			type: 'POST',
			data: params,
			traditional: true,
			success: function(e){
				var data = eval( '(' + e + ')' );
				var items = data['items'];
				if (items != null) {
					for (var i = 0; i < items.length; i++) {
						_ary[items[i]['id']] = items[i];

					}
				}
			},
			error: function(e){
				//console.dir(e);
			}
		});
	}
});
